package net.haiyue.api.custom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public JsonResult baseExceptionErrorHandler(HttpServletRequest req, BaseException e) {
        logger.error(e.getCode() + " " + e.getMsg());
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", e.getCode());
        map.put("message", e.getMsg());
        map.put("path", req.getRequestURI());
        map.put("params", req.getQueryString());
        return JsonResult.error(map);
    }

    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseBody
    public JsonResult noHandlerFoundExceptionHandler(HttpServletRequest req, NoHandlerFoundException e) {

        Map<String, Object> map = new HashMap<>(4);
        map.put("code", "9404");
        map.put("message", "找不到您要访问的接口地址");
        map.put("path", req.getRequestURI());
        map.put("params", req.getQueryString());

        return JsonResult.error(map);
    }

    @ExceptionHandler(value = DataIntegrityViolationException.class)
    @ResponseBody
    public JsonResult dataIntegrityViolationExceptionHandler(HttpServletRequest req, DataIntegrityViolationException e) {
        logger.error(e.getMessage());
        Map<String, Object> map = new HashMap<>(3);
        map.put("message", "此数据有关联或者其他完整性错误!");
        map.put("path", req.getRequestURI());
        map.put("params", req.getQueryString());
        return JsonResult.error(map);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonResult defaultErrorHandler(HttpServletRequest req, Exception e) {
        logger.error(e.getMessage());
        Map<String, String> map = new HashMap<>(4);
        map.put("code", "9500");
        map.put("message", e.getMessage());
        map.put("path", req.getRequestURI());
        map.put("params", req.getQueryString());
        return JsonResult.error(map);
    }
}